package net.eicp.jxcontent.core.snippet

import net.liftweb.common._
import net.liftweb.http._
import net.eicp.jxcontent.core.util._
import scala.xml._

case class JXCenterSnippet(snippetClasses: List[(JXDispatchSnippet, PluginLevel)]) extends DispatchSnippet with Logger {
  
  override def dispatch = {
    case dispatchName if snippetClasses.exists{case (snippetDispatch, level) => snippetDispatch.dispatch.isDefinedAt(dispatchName)} => {
      import scala.language.reflectiveCalls
      val xhtmlTrans = snippetClasses.collect{
        case (snippetDispatch, level) if snippetDispatch.dispatch.isDefinedAt(dispatchName) =>
          //copyObject是在新建对象时用宏eval出来的方法。
          (snippetDispatch, level)
      }
      tranXhtml(xhtmlTrans)(dispatchName) _
    }
  }
  
  def tranXhtml(xhtmlProcess: List[(JXDispatchSnippet, PluginLevel)])(dispatchName: String)(xhtml: NodeSeq): NodeSeq = {
    val snippetScope = new JXSnippetScope()
    val xhtmlProcessChannel = xhtmlProcess
      .sortWith{case((_, PluginLevel(_, x)), (_, PluginLevel(_, y))) => x > y}
      .map{case (dispatchSnippet, level) => {
        dispatchSnippet.dispatch(dispatchName)(snippetScope)
      }}.reduceLeft(_ & _)
    
    def getLevel(processElem: JXProcessElem) = processElem match {
      case JXProcessElemAny(level, _) => level.level
      case JXProcessElemXhtml(level, _) => level.level
      case _ => throw new Exception("JXProcessElem获取不到等级参数")
    }
    
    val outXhtml = xhtmlProcessChannel.processElem.sortWith(getLevel(_) >= getLevel(_))
      .foldLeft(xhtml)((xhtmlIn, process) => {
        process match {
          case JXProcessElemAny(level, process) => { process(); xhtmlIn }
          case JXProcessElemXhtml(level, process) => process(xhtmlIn)
        }
      })
    
    outXhtml
  }
}